package cn.zurish.cloud.work.modbus;

import com.ghgande.j2mod.modbus.io.ModbusTCPTransaction;
import com.ghgande.j2mod.modbus.msg.ReadMultipleRegistersRequest;
import com.ghgande.j2mod.modbus.msg.ReadMultipleRegistersResponse;
import com.ghgande.j2mod.modbus.net.TCPMasterConnection;
import com.ghgande.j2mod.modbus.procimg.Register;

import java.net.InetAddress;

public class MCGSProModbusReader {

    private static final int MODBUS_PORT = 502;
    private static final int UNIT_ID = 1; // 设备单元ID，根据实际情况调整

    /**
     * 读取ASCII字符串数据
     * @param host 设备IP地址
     * @param registerAddress 寄存器地址
     * @param wordCount 字数(每个ASCII字符占半个字)
     * @return ASCII字符串
     */
    public static String readAsciiString(String host, int registerAddress, int wordCount) {
        TCPMasterConnection connection = null;
        try {
            InetAddress address = InetAddress.getByName(host);
            connection = new TCPMasterConnection(address);
            connection.setPort(MODBUS_PORT);
            connection.connect();


            // 创建读取多个寄存器请求
            ReadMultipleRegistersRequest request = new ReadMultipleRegistersRequest(
                    registerAddress, wordCount);
            request.setUnitID(UNIT_ID);

            // 执行事务
            ModbusTCPTransaction transaction = new ModbusTCPTransaction(connection);
            transaction.setRequest(request);
            transaction.execute();

            // 获取响应
            ReadMultipleRegistersResponse response = (ReadMultipleRegistersResponse)
                    transaction.getResponse();

            // 转换为ASCII字符串
            return convertRegistersToAsciiString(response.getRegisters());

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
    }

    /**
     * 将寄存器数组转换为ASCII字符串
     * @param registers 寄存器数组
     * @return ASCII字符串
     */
    private static String convertRegistersToAsciiString(Register[] registers) {
        StringBuilder sb = new StringBuilder();
        for (Register register : registers) {
            int value = register.getValue();
            // 高字节
            byte highByte = (byte) ((value >> 8) & 0xFF);
            if (highByte != 0) { // 忽略空字符
                sb.append((char) highByte);
            }
            // 低字节
            byte lowByte = (byte) (value & 0xFF);
            if (lowByte != 0) { // 忽略空字符
                sb.append((char) lowByte);
            }
        }
        return sb.toString().trim();
    }


    public static void main(String[] args) {
        String host = "localhost"; // 替换为实际设备IP地址

        // 读取设备编号L (地址2625，假设长度为32个字符即16个寄存器)
        String deviceNumberL = readAsciiString(host, 2624, 16);
        System.out.println("设备编号L: " + deviceNumberL);

        // 读取设备编号R (地址2690，假设长度为32个字符即16个寄存器)
        String deviceNumberR = readAsciiString(host, 2689, 16);
        System.out.println("设备编号R: " + deviceNumberR);
    }
}